<template>
  <div class="wrapper">
    <div class="box">
      <WtForm
        ref="wtForm"
        :form-config="formConfig"
        @change="handleFormChange"
        @submit="handleFormSubmit"
        @options-loaded="handleOptionsLoaded"
        @options-error="handleOptionsError"
      />

      <el-divider>操作区域</el-divider>

      <div class="action-buttons">
        <el-button type="primary" @click="getFormData">
          获取表单数据
        </el-button>
        <el-button type="success" @click="reloadCityOptions">
          重新加载城市选项
        </el-button>
        <el-button type="warning" @click="reloadAllOptions">
          重新加载所有选项
        </el-button>
      </div>

      <el-divider>表单数据</el-divider>

      <pre class="data-display">{{ JSON.stringify(formData, null, 2) }}</pre>
    </div>
  </div>
</template>

<script>
import WtForm from '@/components/004-wt-form/index.vue'

// 模拟 API 请求
const mockApi = {
  // 获取城市列表
  getCities: () => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve([
          { label: '北京', value: 'beijing' },
          { label: '上海', value: 'shanghai' },
          { label: '广州', value: 'guangzhou' },
          { label: '深圳', value: 'shenzhen' }
        ])
      }, 1000)
    })
  },

  // 根据省份获取城市
  getCitiesByProvince: province => {
    return new Promise(resolve => {
      setTimeout(() => {
        const cities = {
          jiangsu: [
            { label: '南京', value: 'nanjing' },
            { label: '苏州', value: 'suzhou' },
            { label: '无锡', value: 'wuxi' }
          ],
          zhejiang: [
            { label: '杭州', value: 'hangzhou' },
            { label: '宁波', value: 'ningbo' },
            { label: '温州', value: 'wenzhou' }
          ],
          guangdong: [
            { label: '广州', value: 'guangzhou' },
            { label: '深圳', value: 'shenzhen' },
            { label: '东莞', value: 'dongguan' }
          ]
        }
        resolve(cities[province] || [])
      }, 800)
    })
  },

  // 获取用户角色
  getRoles: () => {
    return [
      { label: '普通用户', value: 'user' },
      { label: '管理员', value: 'admin' },
      { label: '超级管理员', value: 'superadmin' }
    ]
  },

  // 根据角色获取权限
  getPermissionsByRole: role => {
    const permissions = {
      user: [
        { label: '查看', value: 'read' },
        { label: '编辑', value: 'edit' }
      ],
      admin: [
        { label: '查看', value: 'read' },
        { label: '编辑', value: 'edit' },
        { label: '删除', value: 'delete' },
        { label: '审核', value: 'review' }
      ],
      superadmin: [{ label: '所有权限', value: 'all' }]
    }
    return permissions[role] || []
  }
}

export default {
  name: 'FormDemo',
  components: {
    WtForm
  },
  data() {
    return {
      formData: {},
      formConfig: {
        labelWidth: '120px',
        size: 'small',
        gutter: 20,
        formItems: [
          {
            type: 'select',
            label: '用户角色',
            prop: 'role',
            span: 8,
            placeholder: '请选择用户角色',
            // 同步方法 - 立即返回数据
            options: () => mockApi.getRoles(),
            autoLoad: true, // 创建时自动加载
            onChange: (value, formData) => {
              console.log('角色变化:', value)
              // 角色变化时重新加载权限选项
              this.$refs.wtForm.reloadOptions('permissions')
            }
          },
          {
            type: 'checkbox',
            label: '权限设置',
            prop: 'permissions',
            span: 16,
            // 异步方法 - 根据角色动态加载权限
            options: formData => {
              if (!formData.role) {
                return []
              }
              return mockApi.getPermissionsByRole(formData.role)
            },
            // 依赖角色字段，角色变化时自动重新加载
            showCondition: formData => !!formData.role
          },
          {
            type: 'select',
            label: '省份',
            prop: 'province',
            span: 8,
            placeholder: '请选择省份',
            options: () => [
              { label: '江苏省', value: 'jiangsu' },
              { label: '浙江省', value: 'zhejiang' },
              { label: '广东省', value: 'guangdong' }
            ],
            autoLoad: true,
            onChange: value => {
              console.log('省份变化:', value)
              // 省份变化时重新加载城市选项
              this.$refs.wtForm.reloadOptions('city')
            }
          },
          {
            type: 'select',
            label: '城市',
            prop: 'city',
            span: 8,
            placeholder: '请选择城市',
            // 异步方法 - 根据省份获取城市
            options: async formData => {
              if (!formData.province) {
                return []
              }
              return await mockApi.getCitiesByProvince(formData.province)
            },
            showCondition: formData => !!formData.province
          },
          {
            type: 'select',
            label: '常用城市',
            prop: 'commonCity',
            span: 8,
            placeholder: '请选择常用城市',
            // 异步方法 - 模拟接口请求
            options: async () => {
              console.log('开始加载常用城市...')
              const cities = await mockApi.getCities()
              console.log('常用城市加载完成:', cities)
              return cities
            },
            autoLoad: true // 页面加载时自动获取
          },
          {
            type: 'radio',
            label: '项目类型',
            prop: 'projectType',
            span: 12,
            // 同步方法 - 简单返回数据
            options: () => [
              { label: 'Web项目', value: 'web' },
              { label: '移动端项目', value: 'mobile' },
              { label: '桌面应用', value: 'desktop' },
              { label: '小程序', value: 'mini-program' }
            ],
            autoLoad: true
          },
          {
            type: 'select',
            label: '技术栈',
            prop: 'techStack',
            span: 12,
            placeholder: '请选择技术栈',
            // 根据项目类型动态返回技术栈
            options: formData => {
              const techStacks = {
                web: [
                  { label: 'Vue.js', value: 'vue' },
                  { label: 'React', value: 'react' },
                  { label: 'Angular', value: 'angular' }
                ],
                mobile: [
                  { label: 'React Native', value: 'rn' },
                  { label: 'Flutter', value: 'flutter' },
                  { label: '原生开发', value: 'native' }
                ],
                desktop: [
                  { label: 'Electron', value: 'electron' },
                  { label: 'Qt', value: 'qt' }
                ],
                'mini-program': [
                  { label: '微信小程序', value: 'wechat' },
                  { label: '支付宝小程序', value: 'alipay' }
                ]
              }

              return techStacks[formData.projectType] || []
            },
            showCondition: formData => !!formData.projectType
          },
          {
            type: 'input',
            label: '项目名称',
            prop: 'projectName',
            span: 24,
            placeholder: '请输入项目名称'
          }
        ],
        buttons: {
          align: 'right',
          options: [
            {
              label: '提交',
              type: 'primary',
              action: 'submit'
            },
            {
              label: '重置',
              action: 'reset'
            }
          ]
        }
      }
    }
  },
  methods: {
    handleFormChange(data) {
      this.formData = data
      console.log('表单数据变化:', data)
    },

    handleFormSubmit(data) {
      console.log('表单提交:', data)
      this.$message.success('表单提交成功！')
    },

    handleOptionsLoaded(prop, options) {
      console.log(`选项加载完成 ${prop}:`, options)
      this.$message.success(`${prop} 选项加载完成`)
    },

    handleOptionsError(prop, error) {
      console.error(`选项加载失败 ${prop}:`, error)
      this.$message.error(`${prop} 选项加载失败`)
    },

    getFormData() {
      this.formData = this.$refs.wtForm.getFormData()
      this.$message.success('已获取表单数据')
    },

    reloadCityOptions() {
      this.$refs.wtForm.reloadOptions('city')
      this.$message.info('正在重新加载城市选项...')
    },

    reloadAllOptions() {
      this.$refs.wtForm.reloadAllOptions()
      this.$message.info('正在重新加载所有选项...')
    }
  }
}
</script>
